package com.xinchao.ck_mips.utils;

import com.xinchao.ck_mips.constant.HttpConfig;
import com.xinchao.ck_mips.exception.RequestException;
import com.xinchao.ck_mips.http.CKRequestSubscriber;
import com.xinchao.ck_mips.http.CKResponse;
import com.xinchao.rxtools.rxhttp.tools.JsonUtils;
import com.xinchao.rxtools.rxhttp.tools.RxAndroidTools;

import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * 网络请求的接口
 */
public class RequestUtils {

    /**
     * 请求网络回到主线程
     */
    public static <T> void request(Flowable<CKResponse<T>> flowable, CKRequestSubscriber<T> listener) {
        flowable.compose(addFilter()).compose(RxAndroidTools.applySchedulers()).subscribe(listener);
    }

    public static <T> void requestIoThread(Flowable<CKResponse<T>> flowable, CKRequestSubscriber<T> listener) {
        flowable.compose(addFilter()).subscribeOn(Schedulers.io()).subscribe(listener);
    }

    /*public static <T> FlowableTransformer<CKResponse<T>, CKResponse<T>> addFilter() {
        return upstream -> upstream.filter((Predicate<CKResponse<T>>) bean -> {
            if (bean.getCode() != 0) {
                throw new RequestException(bean);
            } else {
                return true;
            }
        });
    }*/

    /**
     * 添加网络连接器
     */
    private static <T> FlowableTransformer<CKResponse<T>, CKResponse<T>> addFilter() {
        return upstream -> upstream.filter((Predicate<CKResponse<T>>) bean -> {
            // 过滤正常状态码
            switch (bean.getCode()) {
                case HttpConfig.StatusCode.SUCCESS:
                    return true;
                case HttpConfig.StatusCode.REGISTERED:
                    return true;
                case HttpConfig.StatusCode.VALIDATE_FAIL:
                    throw new RuntimeException(bean.getCode() + bean.getMsg());
                case HttpConfig.StatusCode.DENIED:
                    throw new RuntimeException(bean.getCode() + bean.getMsg());
                case HttpConfig.StatusCode.NOT_REGIST:
                    throw new RuntimeException(bean.getCode() + bean.getMsg());
                case HttpConfig.StatusCode.TOKEN_INVALID:
                    throw new RuntimeException(bean.getCode() + bean.getMsg());
                default:
                    throw new RuntimeException(JsonUtils.toJson(bean));
            }
        });
    }

}
